from django.contrib.auth.decorators import login_required
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.http import HttpResponse
from models import * 
from django.core import serializers

@login_required
def index(request, success_url=None, 
             template_name='www/index.html',
             extra_context=None): 
    """
		to show home page with links,  admin 
		and dataviewer, search, rapport, custom forms
	"""
  
    
    if extra_context is None:
        extra_context = {}     
        
    
        
    context = RequestContext(request)
    for key, value in extra_context.items():
        context[key] = callable(value) and value() or value
        
    return render_to_response(template_name, context_instance=RequestContext(request))



@login_required
def barcode(request, sn):
   """
		test function, currently is used /templates/www/pdflabel
   """
   response = HttpResponse(mimetype='application/pdf')
   response['Content-Disposition'] = 'attachment; filename=barcode.pdf'
   p = canvas.Canvas(response)
   p.drawString(100, 100, "Hello world.")
   p.showPage()
   p.save()
   return response


@login_required
def stock_component_total(request, id=None, template_name='blank.html'):
	"""
		calculation of total in stock component model
	"""
	actions = ActionStockComponent.objects.filter(componet__exact=id)
	total = 0
	for action in actions:
		if action.action_type == "IN":
			total += action.number
		else:
			total -= action.number
	
	data = {
				"total":total
			} 
	
	return render_to_response(template_name, data, context_instance=RequestContext(request))

@login_required
def select_product_owner(request, id=None, template_name='blank.html'):
   """
	  select locations from model return string in json format	
   """
   locations = LocationAtOwner.objects.filter(owner__exact=id)
   # don't use serializers like that 
   #json  = serializers.serialize('json', locations, fields=('id','description'))
   # it dosn't work, this must be removed []
   data = {
                "locations":locations
            }
   return render_to_response(template_name, data, context_instance=RequestContext(request))
